﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class AreaRepository : BaseRepository<TArea>, IAreaRepository
    {
        public AreaRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }
        /// <summary>
        /// 添加库区
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool AddArea(AreaDto obj,out string message)
        {
            message = "";
            try
            {
                var aobj = Context.TAreas.AsNoTracking().FirstOrDefault(x => x.Code == obj.Code);
                if(aobj!=null)
                {
                    message = "编码已存在";
                    return false;
                }
                //库房
                var wobj = Context.TWarehouses.Find(obj.WhId);
                if (wobj!=null && wobj.Status==1)
                {
                    obj.WhCode = wobj.Code;
                    obj.WhName = wobj.Name;
                }
                else
                {
                    message = "库房不存在或已被禁用";
                    return false;
                }
                //库区类型
                var dictemobj = Context.TDictItems.Find(obj.TypeId);
                if (dictemobj != null) 
                {
                    obj.TypeName = dictemobj.ItemName;
                }
                TArea area = new TArea();
                area = Mapper.Map<TArea>(obj);
                area.CreateUserId = obj.NowUserId;
                area.CreateUserName = obj.NowUserRealName;
                area.CreateDate = DateTime.Now;
                Context.TAreas.Add(area);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 库区显示（弃用）
        /// </summary>
        /// <param name="kcode"></param>
        /// <param name="kname"></param>
        /// <param name="kid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<AreaDto> GetAreaList(string kname, int kid, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var alist = Context.TAreas.AsQueryable();
                var blist = Context.TWarehouses.AsQueryable();
                if (!string.IsNullOrEmpty(kname))
                {
                    alist = alist.Where(c => c.Name.Contains(kname));
                }
                if (kid > 0)
                {
                    alist = alist.Where(x => x.WhId == kid);
                }
                var query = from A in alist
                            join B in blist
                            on A.WhId equals B.Id
                            select new AreaDto
                            {
                                Id = A.Id,
                                Code = A.Code,
                                Name = A.Name,
                                IsRealArea = A.IsRealArea,
                                WhCode = A.WhCode,
                                WhName = A.WhName,
                                Status = A.Status,
                                TypeId = A.TypeId,
                                TypeName = A.TypeName,
                                Erpcode = A.Erpcode,
                                BuiltArea = A.BuiltArea,
                                Remark = A.Remark,
                                DisplayOrder = A.DisplayOrder,
                                CreateDate = A.CreateDate,
                                CreateUserId = A.CreateUserId,
                                CreateUserName = A.CreateUserName,
                                ModifyDate = A.ModifyDate,
                                ModifyUserId = A.ModifyUserId,
                                ModifyUserName = A.ModifyUserName,
                                ShelfCount = A.ShelfCount,
                                //KId=B.Id,
                                KName = B.Name
                            };
                //var page = new
                //{
                //    totalCount = query.Count(),
                //    query = query.OrderBy(p => p.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList()
                //};
                //return page;
                totalCount = query.Count();
                query = query.OrderBy(x => x.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return query.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除库区
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelArea(int uid)
        {
            try
            {
                var del = Context.TAreas.Find(uid);
                if (del != null)
                {
                    Context.TAreas.Remove(del);
                    return Context.SaveChanges() > 0;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改库区信息
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool UpdateArea(AreaDto u, out string message)
        {
            message = "";
            try
            {
                var aobj = Context.TAreas.AsNoTracking().FirstOrDefault(x => x.Id != u.Id && x.Code == u.Code);
                if (aobj != null)
                {
                    message = "编码已存在！";
                    return false;
                }
                //库房
                var wobj = Context.TWarehouses.Find(u.WhId);
                if (wobj != null && wobj.Status==1)
                {
                    u.WhCode = wobj.Code;
                    u.WhName = wobj.Name;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                //库区类型
                var dictemobj = Context.TDictItems.Find(u.TypeId);
                if (dictemobj != null)
                {
                    u.TypeName = dictemobj.ItemName;
                }
                TArea area = new TArea();
                area = Mapper.Map<TArea>(u);
                u.ModifyDate = DateTime.Now;
                u.ModifyUserId = u.NowUserId;
                u.ModifyUserName = u.NowUserRealName;
                Context.TAreas.Update(area);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据id获取数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TArea GetAreaById(int id)
        {
            try
            {
                return Context.TAreas.Find(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取库房(仓库)信息
        /// </summary>
        /// <returns></returns>
        public List<TWarehouse> GetTwarehouseList()
        {
            try
            {
                return Context.TWarehouses.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 库区显示
        /// </summary>
        /// <param name="kname"></param>
        /// <param name="wid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TArea> GetAreanList(string kname, int wid, int pageIndex, int pageSize, out int totalCount)
        {
            var alist = Context.TAreas.AsQueryable();

            //名称
            if(!string.IsNullOrEmpty(kname))
            {
                alist = alist.Where(x => x.Name.Contains(kname));
            }
            //库房
            if(wid!=0)
            {
                alist = alist.Where(x => x.WhId == wid);
            }
            totalCount= alist.Count();
            alist = alist.OrderBy(a => a.DisplayOrder).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return alist.ToList();
        }

        /// <summary>
        /// 根据库房获取库区
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TArea> GetWhIdAreaList(int wid)
        {
            var alist = Context.TAreas.Where(x => x.WhId == wid);

            return alist.ToList();
        }
    }
}
